<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item>
          <el-input
            size="small"
            style="min-width: 210px"
            v-model="listQuery.name"
            placeholder="工程名称"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            size="small"
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        stripe
        highlight-current-row
        style="width: 100%"
        size="small"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-row :gutter="30">
              <el-col :span="12">
                <el-table
                  :data="scope.row.inspectors"
                  border
                  v-if="scope.row.inspectors.length > 0"
                  size="mini"
                >
                  <el-table-column
                    align="center"
                    label="人员类型"
                    prop="category_name"
                    width="200"
                  />
                  <el-table-column
                    label="人员姓名"
                    prop="name"
                  ></el-table-column>
                </el-table>
              </el-col>
              <!-- <el-col :span="12">
                <el-table
                  :data="scope.row.documents"
                  border
                  v-if="scope.row.documents.length > 0"
                  size="mini"
                >
                  <el-table-column
                    align="center"
                    label="资料类型"
                    prop="doc_type_name"
                    width="200"
                  />
                  <el-table-column label="文件名称" prop="name">
                    <template slot-scope="docs">
                      <el-link :href="docs.row.content">{{
                        docs.row.name
                      }}</el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col> -->
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.width : 'center'"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" :width="190">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getBusinessList"
      />
    </el-card>
    <!-- 录入 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="800px"
      top="30px"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 20px"
        status-icon
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="project">
              <el-input
                v-model="form.project"
                placeholder="工程名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期" prop="bid_date">
              <el-date-picker
                v-model="form.bid_date"
                type="date"
                placeholder="日期"
                value-format="yyyy-MM-dd"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="bid_type">
              <el-select v-model="form.bid_type" placeholder="类型" clearable>
                <el-option
                  v-for="item in bidTypes"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="amount">
              <el-input-number
                v-model="form.amount"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用" prop="fees">
              <el-input v-model="form.fees" placeholder="费用" clearable>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="manager">
              <el-input
                v-model="form.manager"
                placeholder="项目经理"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="参与人" prop="persons">
              <el-input v-model="form.persons" placeholder="参与人" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="居间人" prop="broker">
              <el-input v-model="form.broker" placeholder="居间人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居间费" prop="broker_fees">
              <el-input
                v-model="form.broker_fees"
                placeholder="居间费"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName" stretch>
          <el-tab-pane label="检查人员" name="0">
            <el-table :data="form.inspectors" border size="mini" width="100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column label="人员分类" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'inspectors.' + scope.$index + '.category'"
                    :rules="formRules.category"
                  >
                    <el-select
                      v-model="scope.row.category"
                      placeholder="人员分类"
                    >
                      <el-option
                        v-for="item in categories"
                        :label="item.label"
                        :value="item.value"
                        :key="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="姓名" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'inspectors.' + scope.$index + '.name'"
                    :rules="formRules.name"
                  >
                    <el-input
                      v-model="scope.row.name"
                      placeholder="姓名"
                      size="mini"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <el-button
                      type="danger"
                      size="mini"
                      circle
                      icon="el-icon-delete"
                      @click="handleItemDelete(scope)"
                    ></el-button>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- <el-tab-pane label="投标明细" name="1">
            <el-table :data="form.documents" border size="mini" width="100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column
                label="资料类型"
                align="center"
                prop="doc_type_name"
                :width="180"
              >
              </el-table-column>
              <el-table-column label="存档资料" align="left" prop="name">
                <template slot-scope="scope">
                  <el-link :href="scope.row.content">{{
                    scope.row.name
                  }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <el-button
                      type="danger"
                      size="mini"
                      circle
                      icon="el-icon-delete"
                      @click="handleItemDelete(scope)"
                    ></el-button>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane> -->
        </el-tabs>
      </el-form>
      <div slot="footer">
        <el-button
          style="margin-right: 40px"
          type="default"
          size="small"
          @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button
          v-if="activeName == '0'"
          type="success"
          size="mini"
          icon="el-icon-plus"
          @click="handleItemAdd"
          >新增行</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <!-- <el-button
          v-if="activeName == '1'"
          type="success"
          size="small"
          @click="handleSave(true)"
          >保存并上传资料</el-button
        > -->
      </div>
    </el-dialog>
    <!-- 上传文件弹框 -->
    <el-dialog
      title="文档资料上传"
      :visible.sync="uploadDlgVisible"
      width="45%"
    >
      <el-form
        :model="uploadForm"
        ref="uploadFormRef"
        size="small"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        status-icon
      >
        <el-form-item label="工程名称">
          <el-input
            v-model="form.project"
            placeholder="工程名称"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item prop="doc_type" label="资料类型">
          <el-select
            v-model="uploadForm.doc_type"
            placeholder="资料类型"
            clearable=""
          >
            <el-option
              v-for="item in docTypes"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文档" prop="content">
          <el-upload
            ref="upload"
            name="content"
            action="/api/building/bid_file_upload/"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            multiple
            :file-list="uploadForm.fileList"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.rar,.zip,.PDF,.DOC,.DOCX,.XLS,.XLSX,.RAR,.ZIP, .jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-table
          style="width: 100%; margin-top: 30px"
          border
          highlight-current-row
          size="small"
          :data="form.documents"
        >
          <el-table-column label="#" align="center" type="index">
          </el-table-column>
          <el-table-column
            label="资料类型"
            prop="doc_type_name"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            label="文档"
            prop="name"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <el-link :href="scope.row.content">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80px">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="handleFileItemDelete(scope)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDlgVisible = false" size="small"
          >关闭</el-button
        >
      </span>
    </el-dialog>
    <!-- 上传文件弹框  end-->
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getBidBusinesses,
  addBidBusiness,
  updateBidBusiness,
  delBidBusiness,
  delBidInspector,
  delBidDocument,
  getProjectList,
  bidType_list,
} from "@/api/building";

import { formatDateTime } from "@/utils/datetime";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  project: null,
  bid_date: null,
  bid_type: null,
  amount: 0,
  fees: 0,
  manager: null,
  persons: null,
  broker: null,
  broker_fees: 0,
  remark: null,
  user: null,
  inspectors: [],
  documents: [],
};

const defInspectorForm = {
  id: undefined,
  category: null,
  name: null,
};

const defUploadForm = {
  bid_id: null,
  doc_type: null,
  content: null,
  fileList: [],
};

export default {
  name: "Business",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value < 0) {
          callback(new Error("必须大于等于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      uploadForm: Object.assign({}, defUploadForm),

      formRules: {
        project: [
          { required: true, message: "请选择工程名称", trigger: "blur" },
        ],
        bid_date: [{ required: true, message: "请选择时间", trigger: "blur" }],
        fees: [{ validator: checkMoney, trigger: "blur" }],
        broker_fees: [{ validator: checkMoney, trigger: "blur" }],
        name: [{ required: true, message: "请输入人员姓名", trigger: "blur" }],
        category: [
          { required: true, message: "请选择人员类型", trigger: "blur" },
        ],
      },

      tableColumns: [
        {
          key: "project",
          title: "工程名称",
          align: "left",
        },
        {
          key: "bid_date",
          title: "时间",
          width: "100",
        },
        {
          key: "bid_type_name",
          title: "类型",
          width: "80",
        },
        {
          key: "amount",
          title: "数量",
          width: "80",
        },
        {
          key: "fees",
          title: "费用(元)",
          width: "120",
        },
        {
          key: "manager",
          title: "项目经理",
          width: "100",
        },
        {
          key: "persons",
          title: "参与人",
        },
        {
          key: "broker",
          title: "居间人",
          width: "100",
        },
        {
          key: "broker_fees",
          title: "居间费",
          width: "100",
        },
        {
          key: "remark",
          title: "备注",
          width: "180",
        },
      ],
      title: "投标业务",

      dialogVisible: false,
      uploadDlgVisible: false,
      dialogType: "new",
      datas: [],
      projects: [],
      bidTypes: [],
      total: 0,
      listLoading: true,
      activeName: "0",
      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        search_date: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      categories: [
        { value: 1, label: "土建" },
        { value: 2, label: "安装" },
        { value: 3, label: "投标文件" },
      ],
      docTypes: [
        { value: 1, label: "招标文件" },
        { value: 2, label: "投标文件" },
        { value: 3, label: "计价" },
      ],
    };
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        bid_id: this.uploadForm.bid_id,
        doc_type: this.uploadForm.doc_type,
      };
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getBusinessList();
    this.getAllProject();
    this.getBidType();
  },
  methods: {
    getBusinessList() {
      this.listLoading = true;
      getBidBusinesses(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取数据失败!");
          this.listLoading = false;
        });
    },
    getAllProject() {
      getProjectList()
        .then((res) => {
          this.projects = res;
        })
        .catch((error) => {
          this.$message.error("获取工程列表失败!");
        });
    },
    //上传前
    handleBeforeUpload(file) {
      if (this.uploadForm.doc_type == null) {
        this.$message.error("请选择资料类型");
        return false;
      }
      const flag = file.size / 1024 / 1024 < 10;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return flag;
    },

    handleSuccess(res, file, filelist) {
      console.log(res);
      this.form.documents.push(res.file);
    },

    handleUpload(scope) {
      this.form = scope.row;
      this.uploadForm = Object.assign({}, defUploadForm);
      this.uploadForm.archive_id = scope.row.id;
      this.uploadDlgVisible = true;
    },

    //获取标书类型数据列表
    getBidType() {
      this.listLoading = true;
      bidType_list()
        .then((res) => {
          this.bidTypes = res;
        })
        .catch((error) => {
          this.$message.error("获取类型失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getBusinessList();
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    //增加行
    handleItemAdd() {
      this.form.inspectors.push(Object.assign({}, defInspectorForm));
    },

    // 修改
    handleEdit(scope) {
      this.form = scope.row;

      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delBidBusiness(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    //删除行
    handleItemDelete(scope) {
      console.log(scope);
      let row = scope.row;

      if (row.id == undefined || row.id == null) {
        if (this.activeName === "0") {
          this.form.inspectors.splice(scope.$index, 1);
        }
      } else if (row.id > 0) {
        this.$confirm("确定要删除吗?", "删除提示：", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              let res = null;
              if (this.activeName === "0") {
                res = await delBidInspector(row.id);
                this.form.inspectors.splice(scope.$index, 1);
              } else {
                res = await delBidDocument(row.id);
                this.form.documents.splice(scope.$index, 1);
              }
              this.$message({ type: "success", message: "删除成功!" });
            } catch (err) {
              this.$message.error("删除失败!");
            }
          })
          .catch((error) => {});
      }
    },

    handleFileItemDelete({ $index, row }) {
      this.$confirm("确定要删除此投标资料吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delBidDocument(row.id);
          this.form.documents.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    //格式化
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "fees") {
        return row.fees && row.fees.toFixed(2);
      } else if (column.property == "broker_fees") {
        return row.broker_fees && row.broker_fees.toFixed(2);
      } else {
        return cellValue;
      }
    },

    //
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "fees" || column.property === "broker_fees") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateBidBusiness(this.form);
          const index = this.datas.findIndex((v) => v.id === res.id);
          this.datas.splice(index, 1, res);
          this.form = res;
        } else {
          this.form.user = this.uid;
          res = await addBidBusiness(this.form);
          const { id } = res;
          if (id > 0) {
            this.datas.unshift(res);
          }
        }

        const { project, fees, manager } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>工程名称: ${project}</div>
              <div>费用: ${fees}</div>
              <div>项目经理: ${manager}</div>
            `,
          type: "success",
        });

        if (flag) {
          this.uploadDlgVisible = true;

          this.uploadForm = Object.assign({}, defUploadForm);
          this.uploadForm.bid_id = res.id;
          this.$nextTick(() => {
            this.dialogVisible = false;
            this.$refs.upload.clearFiles();
          });
        } else {
          this.dialogVisible = false;
        }
      });
    },
  },
};
</script>

<style lang='scss' scoped>
</style>